﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Crosland.Automotriz.Logic.Linq;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
using Crosland.Automotriz.Seguridad.Business;
using Crosland.Automotriz.Seguridad.Entity;

namespace Crosland.Automotriz.Web.Vehiculos
{
    public partial class wFrmStockDealerIntranetSupervisor : System.Web.UI.Page
    {
        string idNegocio = ConfigurationManager.AppSettings["Negocio"];
        const string script = "MostrarAlerta();";
        bool bounded;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack == false) 
            {
                Panel img = (Panel)Master.FindControl("asp");
                img.Visible = false;

                Panel img2 = (Panel)Master.FindControl("pnlTop");
                img2.Visible = false;


                ListaAnio();
                ListarMarcas();
                ListarVendedor();
                
                if (Request.QueryString["anio"] != null && Request.QueryString["mes"] != null && Request.QueryString["marca"] != null && Request.QueryString["sup"] != null)
                {
                    cboAño.SelectedValue = Request.QueryString["anio"];
                    cboMes.SelectedValue = Request.QueryString["mes"];
                    cboMarca.SelectedValue = Request.QueryString["marca"];
                    cboSupervisor.SelectedValue = Request.QueryString["sup"];
                }
                else 
                {
                    string id_usuario = Session["User"].ToString();
                    cboAño.SelectedValue = DateTime.Now.Year.ToString();
                    cboMes.SelectedValue = DateTime.Now.Month.ToString();
                    cboMarca.SelectedIndex = 0;
                    int id_Vendedor = 0;
                    clsT_Seg_Usuario_VendedorLogic bl = new clsT_Seg_Usuario_VendedorLogic();
                    List<clsT_Seg_Usuario_Vendedor> lista = new List<clsT_Seg_Usuario_Vendedor>();
                    lista = bl.lista(id_usuario);
                    if (lista != null)
                    {
                        if (lista.Count > 0)
                        {
                            id_Vendedor = lista[0].ID_VENDEDOR;
                            cboSupervisor.SelectedValue = id_Vendedor.ToString();
                            cboSupervisor.Enabled = false;
                        }
                        else 
                        {
                            //No tiene un supervisor asignado
                            lblMensaje0.Text = "No tiene supervisor asignado";
                            ScriptManager.RegisterStartupScript(this, typeof(Page), "x", script, true);
                            btnConsultar.Enabled = false;
                            cboAño.Enabled = false;
                            cboMes.Enabled = false;
                            cboMarca.Enabled = false;
                            cboSupervisor.Enabled = false;
                            pv.Enabled = false;
                        }
                    }
                    else 
                    {
                        //No tiene un supervisor asignado
                        lblMensaje0.Text = "No tiene supervisor asignado";
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "x", script, true);
                        btnConsultar.Enabled = false;
                        cboAño.Enabled = false;
                        cboMes.Enabled = false;
                        cboMarca.Enabled = false;
                        cboSupervisor.Enabled = false;
                        pv.Enabled = false;
                    }
                }

                string columnIndexValue = ColumnIndex.Value, rowIndexValue = RowIndex.Value;
                if (!string.IsNullOrEmpty(columnIndexValue) && !string.IsNullOrEmpty(rowIndexValue) && ASPxPopupControl1.ShowOnPageLoad)
                    BindGridView(columnIndexValue, rowIndexValue);
                pv.ClientSideEvents.CellClick = GetJSCellClickHandler();
                ASPxPopupControl1.ClientSideEvents.Closing = GetJSPopupClosingHandler();
            }
        }

        protected void BindGridView(string columnIndex, string rowIndex)
        {
            if (bounded) return;
            bounded = true;
            ASPxGridView1.DataSource = pv.CreateDrillDownDataSource(Int32.Parse(columnIndex), Int32.Parse(rowIndex));
            ASPxGridView1.DataBind();
        }

        protected string GetJSCellClickHandler()
        {
            return string.Format(@"function (s, e) {{
    var columnIndex = document.getElementById('{0}'), rowIndex = document.getElementById('{1}');
    columnIndex.value = e.ColumnIndex;
    rowIndex.value = e.RowIndex;
    GridView.PerformCallback('D');
    ShowDrillDown(e.ColumnIndex);
}}", ColumnIndex.ClientID, RowIndex.ClientID);
        }

        protected string GetJSPopupClosingHandler()
        {
            return string.Format(@"function (s, e) {{
    var columnIndex = document.getElementById('{0}'),
        rowIndex = document.getElementById('{1}');
    columnIndex.value = '';
    rowIndex.value = ''; 
}}", ColumnIndex.ClientID, RowIndex.ClientID);
        }

        void ListaAnio()
        {
            clsTH_VentaBL da = new clsTH_VentaBL();
            IEnumerable<object> años;
            años = da.AniosFactura();
            cboAño.DataSource = años;
            cboAño.DataTextField = "anio";
            cboAño.DataValueField = "anio";
            cboAño.DataBind();
            cboAño.Text = DateTime.Now.Year.ToString();
        }

        void ListarMarcas()
        {
            clsTD_MarcaBL neg = new clsTD_MarcaBL();
            List<Entidad.TD_MARCA> ent = new List<Entidad.TD_MARCA>();
            ent = neg.ListarMarcas();
            cboMarca.DataSource = ent;
            cboMarca.DataTextField = "DES_MARCA";
            cboMarca.DataValueField = "ID_MARCA";
            cboMarca.DataBind();
            cboMarca.SelectedIndex = 0;
        }

        void ListarVendedor()
        {
            clsTD_VendedorBL oVen = new clsTD_VendedorBL();
            cboSupervisor.DataSource = oVen.ListaVendedor();
            cboSupervisor.DataTextField = "NOMBRE_APELLIDO";
            cboSupervisor.DataValueField = "ID_VENDEDOR";
            cboSupervisor.DataBind();
            cboSupervisor.SelectedIndex = 0;
        }

        void Listar() 
        {
            pv.DataBind();
        }

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            Listar();
        }

        protected void btnSalir_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["anio"] != null && Request.QueryString["mes"] != null && Request.QueryString["marca"] != null && Request.QueryString["sup"] != null)
            {
                Response.Redirect("~/Vehiculos/wFrmStockDealerIntranet.aspx?id=" + idNegocio);
            }
            else 
            {
                Response.Redirect("~/Repuestos/wFrmDefault.aspx?id=" + idNegocio);
            }
        }

        protected void ASPxGridView1_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            string[] param = e.Parameters.Split('|');
            if (param[0] != "D") return;
            BindGridView(ColumnIndex.Value, RowIndex.Value);
            ASPxGridView1.PageIndex = 0;
        }

        protected void btnGrabarDetalle_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < ASPxGridView1.VisibleRowCount; i++)
                {
                    int Id_ven_sell_in_out_stock;
                    object values = ASPxGridView1.GetRowValues(i, new string[] { "ID" });
                    Id_ven_sell_in_out_stock = int.Parse(values.ToString());

                    ASPxSpinEdit seCantidad = ASPxGridView1.FindRowCellTemplateControl(i, ASPxGridView1.Columns["Cantidad"] as GridViewDataColumn, "seCantidad") as ASPxSpinEdit;
                    int Cantidad = int.Parse(seCantidad.Value.ToString());

                    clsT_Ven_Sell_In_Out_StockBL neg = new clsT_Ven_Sell_In_Out_StockBL();
                    neg.ActualizarCantidad(Id_ven_sell_in_out_stock, Cantidad);
                }
                Listar();
                lblMensaje.Text = "Datos actualizados satisfactoriamente.";
                ASPxPopupControl1.ShowOnPageLoad = false;
            }
            catch (Exception ex)
            {
                lblMensaje.Text = ex.Message;
            }
        }

        protected void cboMes_SelectedIndexChanged(object sender, EventArgs e)
        {
            Listar();
        }

    }
}